import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Router} from "@angular/router";

@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.scss']
})
export class AddressComponent implements OnInit {
  public title: any = '收货地址';
  public cancel: any = 'assets/cancel/u786.png';
  public showConfirmDel: any = false;
  public showSetConfirm: any = false;
  public showEdit: any = false;
  // 显示地址信息，除非删除才会隐藏
  public showAll: any = [];
  // 显示错误用户名信息
  public errorName: any = false;
  public errorTel: any = false;
  // 编辑框中的信息
  public editMsg: any = [];
  // 存放所有的用户地址
  public allAddressmsg: any = [];
  // 用于控制默认地址选择状态
  public checkArr: any = [];
  public showtabar: any = false;
  // 姓名
  public userName: any = '';
  public tel: any = '';
  public detailaddress: any = '';
  public province: any = '';
  public city: any = '';
  public area: any = '';
  public postalCode: any = '';
  public provinceid: any = '';
  public cityid: any = '';
  public areaid: any = '';
  // show backgroundcolor
  public showColor: any = false;
  // 存放省份
  public provinceArr: any = [];
  // 存放城市
  public cityArr: any = [];
  // 存放地区
  public countArr: any = [];
  public provinceId: any = '';
  public cityId: any = '';
  public areaId: any = '';
  // 省下面的第一个城市
  public firstCity: any = '';
  // 市下面的第一个区域
  public firstCount: any = '';
  // 毫无实在意义
  public k: any;
  constructor( private http: HttpClient, private router: Router) {
  }
  ngOnInit() {
    // 获取用户所有地址
    const api = 'http://192.168.2.228:8080/receive/list?receive_userid=' + 16;
    this.http.get(api).subscribe( res => {
      const arr = res['data'];
      for ( let i = 0; i < arr.length; i++) {
          this.checkArr.push(0);
          this.showAll.push(1);
          if ( arr[i] !== null) {
            if (arr[i]['isdefault'] !== 0 && i !== 0) {
              // 把默认地址打开
              this.checkArr[0] = 1;
              this.checkArr[i] = 0;
              const firstArr = arr[0];
              arr[0] = arr [i];
              arr[i] = firstArr;
              console.log(arr);
              this.allAddressmsg = arr;
            } else if (arr[0]['isdefault'] !== 0) {
              this.checkArr[0] = 1;
              this.checkArr[i] = 0;
              this.allAddressmsg = arr;
            }
          }
      }
    });
    // 获取省
    const url = 'http://192.168.2.228:8080/provinces/list';
    this.http.get(url).subscribe( res => {
      this.provinceArr = res['data'];
    });
  }
  showTabar() {
    this.showtabar = true;
    this.showColor = true;
  }
  closeTabar() {
    this.showtabar = false;
    this.showColor = false;
  }
  showImg(k) {
    this.k = k ;
    // 先判断当前状态
    if ( this.checkArr[k] === 1) {
      // 说明是选中状态，这时候点击是为了取消默认
      this.checkArr[k] = 0;
    } else {
      // 说明是未选中状态，这时候点击是为了添加默认
      // 当前变为1， 其余变为0
      this.showSetConfirm = true;
      this.showColor = true;
    }
  }
  // 删除地址
  delAddress(k) {
    this.k = k;
    this.showConfirmDel = true;
    this.showColor = true;
  }
  // 点击取消按钮
  doCancel() {
    this.showConfirmDel = false;
    this.showColor = false;
  }
  doOk() {
    const api = 'http://192.168.2.228:8080/receive/delete';
    const headers = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
    const params = {
      receive_id: this.allAddressmsg[this.k].receive_id,
      receive_userid: localStorage.user
    };
    this.http.post(api, params, headers).subscribe( res => {
      console.log(res);
      // 删除成功之后，需要把信息隐藏
      if ( res['code'] === 0) {
        this.showAll[this.k] = 0;
        this.showConfirmDel = false;
        this.showColor = false;
      }
    });
  }
  chooseCity() {
    this.cityArr = [];
    this.countArr = [];
    // 获取市
    const api = 'http://192.168.2.228:8080/cities/list?province_id=' + this.provinceId;
    this.http.get(api).subscribe( res => {
      this.cityArr = res['data'];
      this.firstCity = this.cityArr[0];
    });
  }
  chooseCounty() {
    // 获取市下面的地区
    this.countArr = [];
    const api = 'http://192.168.2.228:8080/areas/list?city_id=' + this.cityId;
    this.http.get(api).subscribe( res => {
      this.countArr = res['data'];
      this.firstCount = this.countArr[0];
    });
  }
  // 判断用户名格式
  blurname() {
    const reg = /^([\u4e00-\u9fa5]){2,7}$/;
    if ( !reg.test(this.userName) || this.userName === '') {
      this.errorName = true;
      return false;
    } else {
      this.errorName = false;
      return true;
    }
  }
  // 判断电话号码
  blurtel() {
    if ( this.blurname()) {
      if (!(/^1[3456789]\d{9}$/.test(this.tel)) || this.tel === '') {
        this.errorTel = true;
        return false;
      } else  {
        this.errorTel = false;
        return true;
      }
    }
  }
  // 判断收货详细地址是否为空
  blurDetailaddress( ) {
    if ( this.blurtel()) {
      if ( this.provinceId !== '' && this.cityId !== '' && this.areaId !== '') {
        if ( this.detailaddress !== '') {
          return true;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  // 判断邮编码
  blurpostalCode() {
    if ( this.blurDetailaddress()) {
      if (/[1-9]\d{5}(?!\d)/.test( this.postalCode)) {
        return true;
      } else {
        return false;
      }
    }
  }
  // 提交信息
  doseave() {
    console.log(this.blurpostalCode());
    if ( this.blurpostalCode()) {
      const api = 'http://192.168.2.228:8080/receive/add';
      const head = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };
      const params = {
        receive_userid: localStorage.user,
        provinceid: this.provinceId,
        cityid: this.cityId,
        areaid: this.areaId,
        details: this.detailaddress,
        receive_name: this.userName,
        receive_tel: this.tel
      };
      this.http.post( api, params, head).subscribe( res => {
        console.log(res);
        if ( res['code'] === 0) {
          // 请求成功
          this.showtabar = false;
          this.showColor = false;
          this. userName = '';
          this. tel = '';
          this. detailaddress = '';
          this. postalCode = '';
          this. provinceId = '';
          this. cityId = '';
          this. areaId = '';

          // 请求数据刷新页面

          const api1 = 'http://192.168.2.228:8080/receive/list?receive_userid=' + 16;
          this.http.get(api1).subscribe( result => {
            console.log(result);
            const arr = result['data'];
            console.log(arr);
            for ( let i = 0; i < arr.length; i++) {
              this.checkArr.push(0);
              this.showAll.push(1);
              if ( arr[i]['isdefault'] !== 0 && i !== 0) {
                // 把默认地址打开
                this.checkArr[i] = 1;
                const firstArr = arr[0];
                arr[0] = arr [i];
                arr[i] = firstArr;
                console.log(arr);
                this.allAddressmsg = arr;
              } else {
                this.checkArr[0] = 1;
                this.allAddressmsg = arr;
                console.log(this.allAddressmsg);
              }
            }
          });
        }
      });
    }
  }
  // 点击编辑信息
  editAddress(k) {
    // 现根据k获取信息
    this.k = k;
    const url = 'http://192.168.2.228:8080/receive/detail?receive_id=' + this.allAddressmsg[k].receive_id;
    this.http.get(url).subscribe( res => {
      console.log(res);
      // 把请求到的数据遍历
      this.editMsg = res['data'];
      this.userName = this.editMsg.receive_name;
      this.tel = this.editMsg.receive_tel;
      this.detailaddress = this.editMsg.details;
      this.province = this.editMsg.province_name;
      this.city = this.editMsg.city_name;
      this.area = this.editMsg.area;

    });
    this.showEdit  = true;

  }
  // 关闭编辑框
  closeEdit() {
    this.showEdit = false;
  }
  // 取消设置默认地址
  doSetCancel() {
    this.showColor = false;
    this.showSetConfirm = false;
  }
  doseaveEdit() {
    const api = 'http://192.168.2.228:8080/receive/update';
    const head = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
    const params = {
      receive_id: this.allAddressmsg[this.k].receive_id,
      provinceid: this.provinceId,
      cityid: this.cityId,
      areaid: this.areaId,
      details: this.detailaddress,
      receive_name: this.userName,
      receive_tel: this.tel
    };
    this.http.post(api, params, head).subscribe( res => {
      this.showEdit = false;
      if ( res['code'] === 0) {
        this.showEdit = false;
        const api = 'http://192.168.2.228:8080/receive/list?receive_userid=' + 16;
        this.http.get(api).subscribe( res => {
          console.log(res);
          const arr = res['data'];
          for ( let i = 0; i < arr.length; i++) {
            this.checkArr.push(0);
            this.showAll.push(1);
            if ( arr[i]['isdefault'] !== 0 && i !== 0) {
              // 把默认地址打开
              this.checkArr[0] = 1;
              this.checkArr[i] = 0;
              const firstArr = arr[0];
              arr[0] = arr [i];
              arr[i] = firstArr;
              console.log(arr);
              this.allAddressmsg = arr;
            } else if ( arr[0]['isdefault'] !== 0) {
              this.checkArr[0] = 1;
              this.checkArr[i] = 0;
              this.allAddressmsg = arr;
            }
          }
        });
      }
    });
  }
  // 确定设置默认地址
  doSetOk() {
    this.showColor = false;
    this.showSetConfirm = false;
    for ( let i = 0; i < this.checkArr.length; i++) {
      if ( this.k === i) {
        this.checkArr[this.k] = 1;
        // 调用设置默认地址接口
        const api = 'http://192.168.2.228:8080/receive/setdefault';
        const headers = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json'
          })
        };
        const params = {
          receive_userid: localStorage.user,
          receive_id: this.allAddressmsg[this.k].receive_id
        };
        console.log(this.allAddressmsg[this.k].receive_id);
        this.http.post(api, params, headers).subscribe( res => {
          console.log(res);
          const api1 = 'http://192.168.2.228:8080/receive/list?receive_userid=' + 16;
          this.http.get(api1).subscribe( res => {
            console.log(res);
            const arr = res['data'];
            console.log(arr);
            for ( let i = 0; i < arr.length; i++) {
              this.checkArr.push(0);
              this.showAll.push(1);
              if ( arr[i]['isdefault'] !== 0 && i !== 0) {
                // 把默认放到第一个
                const firstArr = arr[0];
                arr[0] = arr [i];
                arr[i] = firstArr;
                this.checkArr[0] = 1;
                this.checkArr[i] = 0;
                console.log(arr);
                this.allAddressmsg = arr;
              } else if ( arr[0]['isdefault'] !== 0) {
                this.checkArr[0] = 1;
                this.checkArr[i] = 0;
                this.allAddressmsg = arr;
              }
            }
          });
        });
      } else {
        this.checkArr[i] = 0;
      }
    }
  }
}
